package com.kyubi.common.data;

import java.util.Iterator;
import java.util.List;

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Text;
import org.jdom.input.SAXBuilder;

import com.kyubi.common.config.ConfigKeys;
import com.kyubi.common.config.Configuration;

public class XMLToInstanceConvertor {

	private Instances insts = null;
	private String xmlFilePath;
	private Configuration config = Configuration.getSingleton();

	public XMLToInstanceConvertor(String xmlFile) {
		this.xmlFilePath = xmlFile;
	}

	public Instances convert() {
		// return if cached
		if(insts != null) {
			return insts;
		}
		
		insts = new Instances();
		
		try {
			SAXBuilder parser = new SAXBuilder();
			Document doc = parser.build(xmlFilePath);
		
			Iterator<Element> itr = doc.getDescendants();
			while(itr.hasNext()) {
				Element elem;
				
				try {
					elem = itr.next();
				} catch(ClassCastException cce) {
					continue;
				}
			
				if(elem.getName().equals(config.get(ConfigKeys.DATA_TAG))) {
					List content = elem.getContent();
					if(content.size() > 0) {
						Text txt = (Text) content.get(0);
						insts.addData(txt.getText());
						
						// TODO put attr name in config
						Attribute attr = elem.getAttribute("class");
						if(attr != null) {
							insts.addLabel(Boolean.parseBoolean(attr.getValue()));
						}
					}
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		return insts;
	}
}
